var express = require('express');
var router = express.Router();
var session = require("express-session");
router.use(session({
    secret:"chenbeibei",
    resave:false,
    saveUninitialized:true
}));
var md5 = require("md5");

var User = require("../bin/user-dao.js");
var Order = require("../bin/order-dao.js");

/* GET users listing. */
// 用户注册接口
router.post("/regist",function(req,res){
  User.find({account:req.body.account})
  .exec(function(err,data){
    if (data.length > 0) {
      res.json({ err: 1, msg: "此用户名已被占用" });
    } else {
      req.body.psw = md5(req.body.psw);
      var u = new User(req.body);
      u.save(function (err) {
        res.json({ err: 0, msg: "注册成功,请登录" });
      });
    }
  });
});

// 用户登录接口
router.post("/login",function(req,res){
  User.findOne({account:req.body.account})
  .exec(function(err,data){
    if(!data){
      res.json({err:1,msg:"此用户不存在"});
    }else{
      if(md5(req.body.psw)==data.psw){
        req.session.user = data;
        res.json({err:0,msg:"登录成功",userintro:data});
      }else{
        res.json({err:1,msg:"密码错误"});
      }
    }
  });
});

// 判断用户是否登录的接口
router.get("/islogin",(req,res)=>{
  // console.log(req.session.user);
  if(req.session.user){
    res.json({err:0,islogin:true,userintro:req.session.user});
  }else{
    res.json({err:1,islogin:false});
  }
});

// 用户退出登录接口
router.get("/quit",function(req,res){
  req.session.user = "";
  res.json({err:0,msg:"退出成功"});
});

// 用户提交订单接口(每提交一次就生成一个新的订单，不管该用户是不是已经购买过这个票)
router.post("/order",function(req,res){
    var param = {
      ticket:req.body.ticket,
      price:req.body.price,
      count:req.body.count,
      date:req.body.date,
      ordernum:req.body.ordernum,
      user:req.session.user._id
    };
    var o = new Order(param);
    o.save(function(err){
      res.json({err:0});
    });
});

//查询渲染支付页面的数据
router.post("/pay",function(req,res){
  // console.log(req.body);
  Order.findOne(req.body)
  .then(data=>{
    res.json({err:0,msg:data});
  });
}); 






module.exports = router;
